<template>
    <div class="phoneKey">
        <!-- 顶部状态栏 -->
        <div class="top">
            <van-icon name="arrow-left" size="20px" @click="goback()" />
            <div>录入信息</div>
        </div>

        <div class="rate">
            <van-steps :active="active">
                <van-step>录入信息</van-step>
                <van-step>下载云闪付APP</van-step>
                <van-step>交易完成</van-step>
            </van-steps>
        </div>
        <!-- 基本信息 -->
        <div class="info">请填写基本信息</div>
        <van-cell-group>
            <van-field v-model="username" required clearable label="姓名" placeholder="请输入姓名" />

            <van-field v-model="idCard" label="身份证号" placeholder="请输入身份证号" required />
        </van-cell-group>

        <!-- 录入人脸 -->
        <div class="face">录入人脸信息</div>
        <!-- <div class="declare"></div> -->
        <div class="imgbox">
            <img :src="headerImage" id="img" alt="" @click="lookImg()">
        </div>
        <div id="takepicture">
            拍照
            <input type="file" id="upload" accept="image/*" @change="upload">
        </div>
        <div id="nextstep" @click="goerweima()">
            下一步
        </div>

    </div>
</template>

<script>
    import { Toast, ImagePreview } from "vant"
    import { mapState, mapActions } from 'vuex'
    import { Step, Steps } from 'vant'
    import { Icon } from 'vant'
    import Exif from 'exif-js'
    export default {
        // 当前组件的名称
        name: 'home',

        data() {
            return {
                active: 0,
                username: "",
                idCard: "",
                img: "",
                input: "",
                headerImage: '', //base64码
                picValue: '',
                url: "https://wallet.95516.com/s/wl/webV3/activity/yhtzB/html/snsIndex.html?r=c31d969e469fb33f458a32dccc72096a&code=yhtzc2c",
                file: "", //文件
                filename: "",
                isDuodu: "",  //判断是否走多度接口,
                base64: "",
                comm_id: ""
            }
        },

        // 在当前组件中添加其他的自定义组件
        components: {

        },

        /*
            在computed中添加mapState
            如果computed中只有一个辅助函数，后面可以直接写成函数名
        */
        computed: mapState(['token', 'userInfo', 'userid']), // this.token相当于this.$store.state.token

        methods: {
            // 图片预览
            lookImg() {
                let headerImage = this.headerImage
                ImagePreview([headerImage]);
            },
            // 安卓
            goerweima() {
                const { username, idCard, headerImage, file, isDuodu, base64, comm_id } = this
                const that = this
                // console.log(isDuodu)
                const formdata = new FormData()
                if (isDuodu == "doordu") {
                    formdata.append('userid', this.userid);
                    formdata.append('id_card', idCard);
                    formdata.append('name', username);
                    formdata.append('file', file);
                    formdata.append('comm_id', comm_id);
                } else {
                    formdata.append('id', this.userid);
                    formdata.append('id_card', idCard);
                    formdata.append('name', username);
                    formdata.append('file', file);
                    formdata.append('uid', this.userid);
                    formdata.append('comm_id', comm_id);
                }
                console.log(formdata)
                let idcardReg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
                if (!username || !idCard) {
                    Toast("请填写姓名和身份证")
                    return
                }
                if (!idcardReg.test(idCard)) {
                    this.$toast('请输入正确的身份证号码');
                    return;
                }
                if (!headerImage) {
                    Toast("请选择照片")
                    return
                }
                if (isDuodu == "doordu") { //走多度接口
                    this.$axios.post("/face/upload", formdata,
                        {
                            headers: {
                                'Content-Type': 'multipart/form-data',
                                'token': this.token,
                            }
                        }
                    ).then((res) => {
                        console.log(res)
                        if (res.data.code == 200) {
                            Toast({
                                message: res.data.message,
                                onClose: () => {
                                    that.$router.push({
                                        name: "submit"
                                    })
                                    plus.runtime.openURL(this.url, function (res) {

                                    })

                                }
                            })

                        } else {
                            Toast(res.data.message)
                        }

                    });
                } else {  //走优图接口
                    this.$axios.post("/addface/camera", formdata,
                        {
                            headers: {
                                'Content-Type': 'multipart/form-data',
                                'token': this.token,
                            }
                        }
                    ).then((res) => {
                        console.log(res)
                        if (res.data.code == 200) {
                            Toast({
                                message: res.data.message,
                                onClose: () => {
                                    that.$router.push({
                                        name: "submit"
                                    })
                                    plus.runtime.openURL(this.url, function (res) {
                                    })

                                }
                            })

                        } else {
                            Toast(res.data.message)
                        }

                    });
                }
            },
            goback() {
                this.$router.back()
            },
            getInputObj() {

                const selectedFile = document.getElementById('input').files[0];
                var reader = new FileReader();
                reader.readAsDataURL(selectedFile);

                reader.onload = (e) => {
                    // console.log("e", e);
                    this.url = e.currentTarget.result
                }
            },
            upload(e) {
                // files为传进来的图片文件
                let files = e.target.files || e.dataTransfer.files;
                if (!files.length) return;
                this.picValue = files[0];
                // console.log("picValue", this.picValue)
                var timestamp = Date.parse(new Date())
                this.filename = timestamp + this.picValue.name
                this.imgPreview(this.picValue);
            },
            imgPreview(file) {
                let self = this;
                let Orientation;
                //去获取拍照时的信息，解决拍出来的照片旋转问题
                Exif.getData(file, function () {
                    Orientation = Exif.getTag(this, 'Orientation');
                });
                // 看支持不支持FileReader
                if (!file || !window.FileReader) return;

                if (/^image/.test(file.type)) {
                    // 创建一个reader
                    let reader = new FileReader();
                    // 将图片2将转成 base64 格式
                    reader.readAsDataURL(file);
                    // 读取成功后的回调
                    reader.onloadend = function () {
                        let result = this.result;
                        let img = new Image();
                        self.base64 = result
                        img.src = result;
                        // console.log( "img",img.src)
                        //判断图片是否小于100K,是就直接上传，反之压缩图片
                        if (this.result.length <= (300 * 1024)) {
                            self.headerImage = this.result;
                            // console.log("base64", self.headerImage)
                            self.file = self.dataURLtoFile(self.headerImage, self.filename)

                            self.postImg();
                        } else {
                            img.onload = function () {
                                let data = self.compress(img, Orientation);
                                self.headerImage = data;
                                // console.log("base64", self.headerImage)
                                self.file = self.dataURLtoFile(data, self.filename)

                                // console.log(data)
                                self.postImg();
                            }
                        }
                    }
                }
            },
            postImg() {
                //这里写接口
                // console.log("000")
            },
            rotateImg(img, direction, canvas) {
                //最小与最大旋转方向，图片旋转4次后回到原方向    
                const min_step = 0;
                const max_step = 3;
                if (img == null) return;
                //img的高度和宽度不能在img元素隐藏后获取，否则会出错    
                let height = img.height;
                let width = img.width;
                let step = 2;
                if (step == null) {
                    step = min_step;
                }
                if (direction == 'right') {
                    step++;
                    //旋转到原位置，即超过最大值    
                    step > max_step && (step = min_step);
                } else {
                    step--;
                    step < min_step && (step = max_step);
                }
                //旋转角度以弧度值为参数    
                let degree = step * 90 * Math.PI / 180;
                let ctx = canvas.getContext('2d');
                switch (step) {
                    case 0:
                        canvas.width = width;
                        canvas.height = height;
                        ctx.drawImage(img, 0, 0);
                        break;
                    case 1:
                        canvas.width = height;
                        canvas.height = width;
                        ctx.rotate(degree);
                        ctx.drawImage(img, 0, -height);
                        break;
                    case 2:
                        canvas.width = width;
                        canvas.height = height;
                        ctx.rotate(degree);
                        ctx.drawImage(img, -width, -height);
                        break;
                    case 3:
                        canvas.width = height;
                        canvas.height = width;
                        ctx.rotate(degree);
                        ctx.drawImage(img, -width, 0);
                        break;
                }
            },
            compress(img, Orientation) {
                let canvas = document.createElement("canvas");
                let ctx = canvas.getContext('2d');
                //瓦片canvas
                let tCanvas = document.createElement("canvas");
                let tctx = tCanvas.getContext("2d");
                let initSize = img.src.length;
                let width = img.width;
                let height = img.height;
                //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
                let ratio;
                if ((ratio = width * height / 4000000) > 1) {
                    console.log("大于400万像素")
                    ratio = Math.sqrt(ratio);
                    width /= ratio;
                    height /= ratio;
                } else {
                    ratio = 1;
                }
                canvas.width = width;
                canvas.height = height;
                //        铺底色
                ctx.fillStyle = "#fff";
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                //如果图片像素大于100万则使用瓦片绘制
                let count;
                if ((count = width * height / 1000000) > 1) {
                    console.log("超过100W像素");
                    count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
                    //            计算每块瓦片的宽和高
                    let nw = ~~(width / count);
                    let nh = ~~(height / count);
                    tCanvas.width = nw;
                    tCanvas.height = nh;
                    for (let i = 0; i < count; i++) {
                        for (let j = 0; j < count; j++) {
                            tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                        }
                    }
                } else {
                    ctx.drawImage(img, 0, 0, width, height);
                }
                //修复ios上传图片的时候 被旋转的问题
                if (Orientation != "" && Orientation != 1) {
                    switch (Orientation) {
                        case 6://需要顺时针（向左）90度旋转
                            this.rotateImg(img, 'left', canvas);
                            break;
                        case 8://需要逆时针（向右）90度旋转
                            this.rotateImg(img, 'right', canvas);
                            break;
                        case 3://需要180度旋转
                            this.rotateImg(img, 'right', canvas);//转两次
                            this.rotateImg(img, 'right', canvas);
                            break;
                    }
                }
                //进行最小压缩
                let ndata = canvas.toDataURL('image/jpeg', 0.1);
                // console.log('压缩前：' + initSize);
                // console.log('压缩后：' + ndata.length);
                // console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
                tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
                console.log(ndata)

                return ndata;

            },
            dataURLtoFile(dataurl, filename) {//将base64转换为文件
                var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, { type: mime });
            }
        },
        // 生命周期函数,创建实例,可以获取this,但DOM节点还没有创建出来
        created() {
            console.log('created', this.$el)
        },
        // 生命周期函数,当前组件上的所有DOM节点都已经创建出来
        mounted() {
            this.isDuodu = this.$route.params.isDuodu
            this.comm_id = this.$route.params.comm_id
            console.log("comm_id", this.comm_id, "多度", this.isDuodu)
        },
        // 生命周期函数,当数据发生改变并且导致视图发生相应的改变
        updated() {
            // console.log('updated')
        },
        // 生命周期函数,组件被销毁
        destroyed() {
            console.log("组件销毁", 666)
            console.log('destroyed')
        },

        // 生命周期函数,离开缓存组件
        deactivated() {
            console.log('deactivated')

            // 不要尝试去获取页面的scrollTop,因为页面只有一个,跳转到新的路由,页面的scrollTop会变成0
            // 所以,在离开的时候,把当前组件的scrollTop保存下来,赋给一个新的变量
            // this.cache_scrollTop = this.scrollTop
        },
        // 离开路由之前,它会在deactivated之前调用
        beforeRouteLeave(to, from, next) {
            console.log('beforeRouteLeave')

            this.username = "",
                this.idCard = "",
                this.img = "",
                this.headerImage = '',
                next()
        }
    }
</script>

<!-- 添加scoped属性,将样式的作用域限制在当前组件内,不会影响子组件 -->
<style lang="scss" scoped>
    .phoneKey {
        padding: 50px 0;
    }

    .top {
        position: fixed;
        top: 0;
        height: 40px;
        line-height: 40px;
        /* position: relative; */
        font-size: 16px;
        border-bottom: 1px solid #999;
        width: 100%;
        background-color: white;
        z-index: 9999;
    }

    .top div {
        text-align: center;

    }

    .van-icon-arrow-left {
        position: absolute;
        top: 10px;
    }

    .rate {
        width: 90%;
        margin: .2rem auto;
        /* display: flex;
            justify-content: space-around; */
        /* align-items: center; */
    }

    .num {
        font-size: .5rem;
        height: .8rem;
        width: .8rem;
        border: 1px solid #666;
        border-radius: 50%;
        text-align: center;
        line-height: .8rem;
        margin: 0 auto;
    }

    .van-step__title {
        margin-bottom: 180px !important;
    }

    .face {
        margin-top: .4rem;
    }

    .info,
    .face {
        margin-left: .2rem;
    }

    .declare {
        text-align: center;
        background-color: #07c160;
        color: aliceblue;
        margin-top: .3rem;
        font-size: .28rem;
        height: 1px;
        line-height: .5rem;
    }

    .imgbox {
        width: 55%;
        height: 4.5rem;
        background-image: url("../assets/img/img2/rentou.jpg");
        background-size: 100% 100%;
        margin: .5rem auto 0;
    }

    .imgbox img {
        width: 100%;
        height: 100%;
    }

    #takepicture {
        width: 1.5rem;
        height: .7rem;
        line-height: .7rem;
        border-radius: 4px;
        background-color: #07c160;
        color: rgba(255, 255, 255, 1);
        font-size: 20px;
        text-align: center;
        font-family: Microsoft Yahei;
        border: 1px solid rgba(187, 187, 187, 1);
        margin: .2rem auto;
        max-width: 100px;
        max-height: 50px;
        position: relative;
    }

    #nextstep {

        width: 100%;
        height: 51px;
        border-radius: 4px;
        line-height: 51px;
        background-color: #07c160;
        color: rgba(255, 255, 255, 1);
        font-size: 20px;
        text-align: center;
        font-family: Microsoft Yahei;
        border: 1px solid rgba(187, 187, 187, 1);
        position: fixed;
        bottom: 0;
        z-index: 2;
    }

    #upload {
        width: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        opacity: 0;
    }
</style>